﻿using Digitalmes.Core.Domain.Eitites;
using Digitalmes.Core.Domain.Repositories;

namespace Digitalmes.Core.Services.Impl;

internal sealed class TurntableArchiveService(IRepository<TurntableArchiveRecord> repo, ICounterService counterService) : ITurntableArchiveService
{
    public async Task<(List<TurntableArchiveRecord>, int)> GetPageListAsync(DateTime? startTime, DateTime? endTime, int pageIndex, int pageSize, CancellationToken cancellationToken = default)
    {
        return await repo.AsQueryable()
            .WhereIF(startTime.HasValue, m => m.ArchiveTime >= startTime.MinTime())
            .WhereIF(endTime.HasValue, m => m.ArchiveTime <= endTime.MaxTime())
            .ToPagationAsync(pageIndex, pageSize, cancellationToken).ConfigureAwait(false);
    }

    public async Task<List<TurntableArchiveRecord>> GetListAsync(DateTime? startTime, DateTime? endTime, CancellationToken cancellationToken = default)
    {
        return await repo.AsQueryable()
            .WhereIF(startTime.HasValue, m => m.ArchiveTime >= startTime.MinTime())
            .WhereIF(endTime.HasValue, m => m.ArchiveTime <= endTime.MaxTime())
            .ToListAsync(cancellationToken).ConfigureAwait(false);
    }

    public async Task ArchiveAsync(TurntableArchiveRecord input)
    {
        // 获取转动次数，累加
        var number = await counterService.IncrementOrCreateAsync("number_rotations", "转台转动次数").ConfigureAwait(false);
        input.Number = number;
        await repo.InsertAsync(input).ConfigureAwait(false);
    }
}
